<template>
  <PageContainer>
    <view class="container">
      <Header title="报名详情" />
      <Loading v-model="loading">
        <view class="pa-12">
          <RegisterInfoView
            :register-info="registerInfo"
            :activity-info="activityInfo"
            :applicant-info="applicantInfo"
            @refresh="refresh"
          >
            <template>
              <TButton
                v-if="getShowCancelRegister"
                text="取消报名"
                type="none"
                :icon="'\ue604'"
                :customStyle="{
                  display: 'inline-block',
                  backgroundColor: '#F2F3F5',
                  color: '#333333',
                }"
                custom-class="h-24 linh-24 br-12"
                @click="modalVisible = true"
              />
              <TButton
                text="详细信息"
                type="none"
                :icon="'\ue8bf'"
                :customStyle="{
                  display: 'inline-block',
                  backgroundColor: '#F2F3F5',
                  color: '#333333',
                  marginLeft: '24rpx',
                }"
                custom-class="h-24 linh-24 br-12"
                @click="toRegisterFormForm"
              />
            </template>
          </RegisterInfoView>
          <CellBox title="报名申请信息" :list="applicantInfo" />
          <CellBox v-if="signInfo.length" title="签到信息" :list="signInfo" />
        </view>
        <TButtonGroup
          :styles="{
            backgroundColor: '#fff',
            justifyContent: 'flex-end',
            boxShadow: '0px -4rpx 24rpx 0px rgba(150, 151, 153, 0.16)',
          }"
        >
          <TButton
            v-if="
              ![ApprovalStatusEnum.CANCEL, ApprovalStatusEnum.REJECT].includes(approvalStatus) &&
              activityInfo?.activityType === ActivityTypeEnum.oneself
            "
            text="打印胸卡"
            type="none"
            :customStyle="{
              display: 'inline-block',
              backgroundColor: 'transparent',
              color: '#2878FF',
              border: '1px solid #2878FF',
            }"
            custom-class="h-32 linh-32 br-16 px-12"
            @click="handleShowPrinterPopup"
          />
          <TButton
            text="联系ta"
            type="primary"
            :customStyle="{
              display: 'inline-block',
              marginLeft: '20rpx',
            }"
            custom-class="h-32 linh-32 br-16 px-12"
            @click="makePhoneCall"
          />
        </TButtonGroup>
      </Loading>
    </view>

    <ShowModal
      v-model="modalVisible"
      title="取消报名"
      content-width="100%"
      cancel-text="暂不取消"
      confirm-text="申请取消"
      confirm-color="#EA5E0E"
      :confirm-auto-close="false"
      @confirm="handleCancelRegister"
    >
      <template #content>
        <view class="pa-20" style="width: 100%">
          <view class="fz-14 mb-16" style="color: #969799">
            <text>取消后，如有支付的活动费用将原路退回。</text>
          </view>
          <view style="background-color: #f2f3f5">
            <UniEasyinput v-model="cancelRemark" type="textarea" placeholder="请说明取消报名原因" />
          </view>
        </view>
      </template>
    </ShowModal>

    <SelectPrinter
      v-if="activityInfo?.activityId"
      ref="selectPrinterRef"
      :activity-id="activityInfo.activityId"
    />

    <CancelRegistrationRecord
      v-if="registerInfo?.cancelRecordId"
      v-model:visible="cancelRegistrationRecordVisible"
      :register-id="registerInfo?.id"
      type="admin"
    />
  </PageContainer>
</template>

<script lang="ts" setup>
  /* activityManageRegisterDetail 报名详情 */
  import {
    activityManagerCancelSysRegistration,
    activityManagerRegisterDetail,
  } from '@/api/activity';
  import type { ActivityRegisterTicketUnion, ActivityShortDetailVo } from '@/api/order/types';
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import Loading from '@/components/Loading/index.vue';
  import RegisterInfoView from '../../components/RegisterInfoView.vue';
  import CellBox, { type ListItem as CellBoxListItem } from '../../components/CellBox.vue';
  import SelectPrinter from '../../components/SelectPrinter.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { navigateTo, onLoad } from '@/router';
  import type { ActivityManageRegisterDetail } from '@/router/types/modules';
  import { computed, ref } from 'vue';
  import { RegisterTypeText, getApprovalStatusText } from '@/api/activity/types';
  import { Toast } from '@/utils';
  import {
    ActivityStatusEnum,
    ApprovalStatusEnum,
    SignStatusEnum,
    SignTypeEnumTextMap,
    ActivityTypeEnum,
  } from '@/enums/activityStatusEnum';
  import { onPullDownRefresh } from '@dcloudio/uni-app';
  import CancelRegistrationRecord from '../../components/CancelRegistrationRecord.vue';
  import ShowModal from '@/components/ShowModal/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import { formatMoney } from '@/utils/number';
  const loading = ref(true);
  const registerInfo = ref<ActivityRegisterTicketUnion>();
  const activityInfo = ref<ActivityShortDetailVo>();

  const applicantInfo = ref<CellBoxListItem[]>([]);
  const signInfo = ref<CellBoxListItem[]>([]);

  const cancelRegistrationRecordVisible = ref(false);

  let callback: ActivityManageRegisterDetail['callback'];
  onLoad<'activityManageRegisterDetail'>((op) => {
    callback = op.callback;
    __init(op.registerId);
  });

  const approvalStatus = ref();
  async function __init(registerId?: number) {
    loading.value = true;
    const id = registerInfo.value?.id as number;
    const { activityRegisterUserTicketVo: registerInfoVo, activityShortDetailVo } =
      await activityManagerRegisterDetail(registerId || id);

    registerInfo.value = registerInfoVo;
    activityInfo.value = activityShortDetailVo;
    approvalStatus.value = registerInfoVo.approvalStatus;
    const statusObj = getApprovalStatusText.get(registerInfoVo.approvalStatus);
    const personInfo = `${registerInfoVo.gmatName} ${registerInfoVo.gmatPhone}`;

    const applicantInfoList: CellBoxListItem[] = [
      {
        label: '报名提交人',
        value: personInfo,
      },
      { label: '报名状态', value: statusObj?.text, valueColor: statusObj?.color },
      { label: '报名类型', value: registerInfoVo.ticketName },
    ];

    if (registerInfoVo.totalDiscountMoney > 0) {
      applicantInfoList.push({
        label: `会员优惠`,
        value: `-${formatMoney({ money: registerInfoVo.totalDiscountMoney })}`,
      });
    }

    if (registerInfoVo.totalMoney > 0) {
      applicantInfoList.push({
        label: '费用总价',
        value: formatMoney({ money: registerInfoVo.totalMoney }),
      });
      applicantInfoList.push({
        label: '实付金额',
        value: formatMoney({ money: registerInfoVo.payMoney }),
        valueColor: '#EA5E0E',
      });
    }

    applicantInfoList.push({
      label: '报名来源',
      value: RegisterTypeText[registerInfoVo.registerType],
    });
    applicantInfoList.push({ label: '报名时间', value: registerInfoVo.createTime });

    if (
      registerInfoVo.approvalStatus !== ApprovalStatusEnum.UNDERREVIEW &&
      registerInfoVo.verifyTime &&
      registerInfoVo.registerType !== 'batch'
    ) {
      applicantInfoList.push({
        label: '审核人',
        value: registerInfoVo.verifyName || (registerInfoVo.verifyTime ? '无需审核' : '--'),
      });
      applicantInfoList.push({ label: '审核时间', value: registerInfoVo.verifyTime });
    }

    if (registerInfoVo.approvalStatus === ApprovalStatusEnum.REJECT) {
      applicantInfoList.push({ label: '审核说明', value: registerInfoVo.remarks });
    }

    if (registerInfoVo.cancelRecordId) {
      applicantInfoList.push({
        label: '取消报名记录',
        operation: {
          text: '查看详情',
          callback: () => {
            cancelRegistrationRecordVisible.value = true;
          },
        },
      });
    }

    if (registerInfoVo.approvalStatus !== ApprovalStatusEnum.PASSED) {
      if (registerInfoVo.cancelPersonName) {
        applicantInfoList.push({
          label: '取消人',
          value: registerInfoVo.cancelPersonName,
        });
      }

      if (registerInfoVo.cancelTime) {
        applicantInfoList.push({
          label: '取消时间',
          value: registerInfoVo.cancelTime,
        });
      }
    }

    applicantInfo.value = applicantInfoList;

    if (registerInfoVo.signStatus === SignStatusEnum.YES_SIGN) {
      signInfo.value = [
        {
          label: '签到人',
          value: (() => {
            let str = '';
            if (registerInfoVo.replaceSignPersonName) {
              str = registerInfoVo.replaceSignPersonName + ' ';
            }
            if (registerInfoVo.replaceSignPersonPhone) {
              str += registerInfoVo.replaceSignPersonPhone;
            }
            if (str) return str;
            return '--';
          })(),
        },

        {
          label: '签到状态',
          value: registerInfoVo.signStatus === SignStatusEnum.YES_SIGN ? '已签到' : '未签到',
          valueColor: registerInfoVo.signStatus === SignStatusEnum.YES_SIGN ? '#2878FF' : '#646566',
        },
        { label: '签到时间', value: registerInfoVo.signTime || '--' },
        { label: '签到方式', value: SignTypeEnumTextMap[registerInfoVo.signType] },
        { label: '手写签名', value: registerInfoVo.signImg, valueType: 'img' },
      ];
    }

    loading.value = false;
    uni.stopPullDownRefresh();
  }

  function makePhoneCall() {
    const personTel = registerInfo.value?.personTel;
    if (personTel) {
      uni.makePhoneCall({
        phoneNumber: personTel,
      });
    } else {
      Toast('暂无联系方式');
    }
  }

  const selectPrinterRef = ref<{ show: (registerId: number) => void }>();
  function handleShowPrinterPopup() {
    selectPrinterRef.value?.show(registerInfo.value?.id as number);
  }

  function refresh() {
    callback?.();
    __init();
  }

  const modalVisible = ref(false);
  const cancelRemark = ref<string>('');
  /** 取消报名 */
  function handleCancelRegister() {
    if (!cancelRemark.value) return Toast('请说明取消报名原因');
    activityManagerCancelSysRegistration({
      registerId: registerInfo.value?.id as number,
      remarks: cancelRemark.value,
    })
      .then(() => {
        refresh();
        Toast('取消成功');
      })
      .finally(() => (modalVisible.value = false));
  }

  function toRegisterFormForm() {
    navigateTo({
      name: 'activityRegisterForm',
      options: {
        activityId: activityInfo.value?.activityId,
        id: registerInfo.value?.id as number,
        type: 'activityManage',
      },
    });
  }

  const getShowCancelRegister = computed(() => {
    return (
      (registerInfo.value?.approvalStatus === ApprovalStatusEnum.PASSED ||
        registerInfo.value?.approvalStatus === ApprovalStatusEnum.UNDERREVIEW ||
        registerInfo.value?.approvalStatus === ApprovalStatusEnum.WAITPARTICIPATEIN) &&
      activityInfo.value?.activityStatus !== ActivityStatusEnum.END &&
      activityInfo.value?.activityStatus !== ActivityStatusEnum.CANCEL &&
      registerInfo.value?.signStatus !== SignStatusEnum.YES_SIGN
    );
  });

  onPullDownRefresh(() => __init());
</script>

<style lang="scss" scoped></style>
